package com.qk.exception;

import com.qk.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 捕获所有异常
     */
    @ExceptionHandler
    public Result handlerException(Exception e) {
    log.error("程序运行错误",e);
        return Result.error("服务器异常");
    }

    /**
     * 捕获 DuplicateKeyException 异常
     */
    @ExceptionHandler
    public Result handleDuplicateKeyException(DuplicateKeyException e){
        String errMsg = e.getMessage();
        /* 2324是一个已经存在的部门
        * errMag的结果
        *    ### Error updating database.  Cause: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '2324' for key 'dept.name'
        *    ### The error may exist in com/qk/mapper/DeptMapper.java (best guess)
        *    ### The error may involve com.qk.mapper.DeptMapper.insert-Inline
        *    ### The error occurred while setting parameters
        *    ### SQL: insert into dept(name,status,create_time,update_time) values(?,?,?,?)
        *    ### Cause: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '2324' for key 'dept.name'
        *    ; Duplicate entry '2324' for key 'dept.name'
        * */
        if(errMsg.contains("Duplicate entry")){
            String msg = errMsg.substring(errMsg.indexOf("Duplicate entry"));
            /*
            * msg的结果
            *    Duplicate entry '2324' for key 'dept.name'
            *    ### The error may exist in com/qk/mapper/DeptMapper.java (best guess)
            *    ### The error may involve com.qk.mapper.DeptMapper.insert-Inline
            *    ### The error occurred while setting parameters
            *    ### SQL: insert into dept(name,status,create_time,update_time) values(?,?,?,?)
            *    ### Cause: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '2324' for key 'dept.name'
            *   ; Duplicate entry '2324' for key 'dept.name'
            * */
            String[] arr = msg.split(" ");
            /*
            * arr的结果
            * ["Duplicate", "entry", "'2324'", "for", "key", +39 more]
            * */
            return Result.error(arr[2] + " 已存在");
        }
        return Result.error("对不起, 服务端异常, 请稍后重试 !!");
    }

    /**
     * 处理BusinessException异常
     */
    @ExceptionHandler
    public Result handlerBusinessException(BusinessException e) {
        log.error("业务异常,{}",e.getMessage(),e);
        return Result.error(e.getMessage());
    }

}
